package com.imdroid.lite.activities;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.imdroid.lite.IMDroid;
import com.imdroid.lite.R;
import com.imdroid.lite.model.User;
import com.imdroid.lite.process.ProcessFactory;
import com.imdroid.lite.process.UserProcess;

public class HomeRegisterActivity extends BaseActivity {
	/**
	 * 用户账号
	 */
	private String account;
	/**
	 * 昵称
	 */
	private String nickname;
	/**
	 * 密码
	 */
	private String password;
	/**
	 * 密码
	 */
	private String password_confirm;
	/**
	 * 车队进入密码
	 */
	private String team_access_code;
	/**
	 * 电话号码
	 */
	private String mobile_phone;
	/**
	 * 注册验证吗
	 */
	private String validate_code;
	/**
	 * 车型
	 */
	private String modal;
	/**
	 * 车牌号
	 */
	private String boardplate;
	/**
	 * 是否新用户注册
	 */
	private boolean isNew;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	public void onCreate(Bundle bdl) {
		super.onCreate(bdl);
		setContentView(R.layout.home_register);

		User currentUser = IMDroid.getUser();
		if (currentUser != null) {
			feedUserInformation(currentUser);
		} else {
			Intent in = getIntent();
			String user = in.getStringExtra("user");
			if (user != null && user.trim().length() > 0) {
				((EditText) findViewById(R.id.home_reg_account)).setText(user);
				((EditText) findViewById(R.id.home_reg_nick)).setText(user);
			}
		}

		isNew = (IMDroid.getUser() == null || IMDroid.getUser().getUser_id() <= 0);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onResume()
	 */
	protected void onResume() {
		super.onResume();
		// 判断是新加用户或者用户修改
		this.findViewById(R.id.home_reg_text_registercode_edit).setVisibility(
				(isNew) ? View.VISIBLE : View.GONE);
		this.findViewById(R.id.home_reg_text_registercode_text).setVisibility(
				(isNew) ? View.VISIBLE : View.GONE);

		// 显示退出按钮
		View lo_button = this.findViewById(R.id.home_reg_logout);
		lo_button.setVisibility(!isNew ? View.VISIBLE : View.GONE);
		View mt_button = this.findViewById(R.id.home_reg_match);
		mt_button.setVisibility(!isNew ? View.VISIBLE : View.GONE);

		// 验证码
		View validate_panel = this
				.findViewById(R.id.home_reg_text_registercode_edit);
		validate_panel.setVisibility(isNew ? View.VISIBLE : View.GONE);

		if (!isNew)
			((Button) findViewById(R.id.home_register_button))
					.setText(R.string.home_reg_change);
		// 车机名称
		User currentUser = IMDroid.getUser();
		this.findViewById(R.id.home_reg_text_match_device_title)
				.setVisibility(
						(currentUser != null && currentUser.getParentId() > 0) ? View.VISIBLE
								: View.GONE);
		this.findViewById(R.id.home_reg_text_match_device_edit)
				.setVisibility(
						(currentUser != null && currentUser.getParentId() > 0) ? View.VISIBLE
								: View.GONE);
	}

	/**
	 * Back to the home activity
	 * 
	 * @param view
	 *            the button of back
	 */
	public void back(View view) {
		finish();
	}
	
	public void inviteFriends(View view){
		Uri uri = Uri.parse("smsto:");
		Intent in = new Intent(Intent.ACTION_SENDTO, uri);
		in.putExtra("sms_body", getString(R.string.reg_invite_friend_content));
		startActivity(in);
	}

	/**
	 * The action of register activity
	 * 
	 * @param view
	 *            the button of register
	 */
	public void register(View view) {
		account = ((EditText) this.findViewById(R.id.home_reg_account))
				.getText().toString();
		nickname = ((EditText) this.findViewById(R.id.home_reg_nick)).getText()
				.toString();
		validate_code = ((EditText) this
				.findViewById(R.id.home_reg_register_code)).getText()
				.toString();
		mobile_phone = ((EditText) this.findViewById(R.id.home_reg_mobile))
				.getText().toString();

		password = ((EditText) this.findViewById(R.id.home_reg_password))
				.getText().toString();
		password_confirm = ((EditText) this
				.findViewById(R.id.home_reg_password_confirm)).getText()
				.toString();
		team_access_code = ((EditText) this
				.findViewById(R.id.home_reg_team_access_code)).getText()
				.toString();
		modal = ((EditText) this.findViewById(R.id.home_reg_model)).getText()
				.toString();
		boardplate = ((EditText) this.findViewById(R.id.home_reg_boardplate))
				.getText().toString();

		// 检查输入是否完整
		if (account == null || account.length() <= 4) {
			showAlert(R.string.remind, R.string.home_reg_error_account);
			return;
		} else {
			EditText nickET = ((EditText) findViewById(R.id.home_reg_nick));
			String nick = nickET.getText().toString();
			if ("".equals(nick.trim())) {
				nickET.setText(account);
			}
			nickname = nickET.getText().toString().trim();
		}
		if (isNew && (password == null || password.length() <= 4)) {
			showAlert(R.string.remind, R.string.home_reg_error_password);
			return;
		} else if (password != null && password.length() > 0
				&& password.length() < 4) {
			showAlert(R.string.remind, R.string.home_reg_error_password);
			return;
		}
		if (!password.equals(password_confirm)) {
			showAlert(R.string.remind, R.string.home_reg_error_password_confirm);
			return;
		}
		if (isNew & (validate_code == null || validate_code.length() <= 0)) {
			showAlert(R.string.remind, R.string.home_reg_error_validate_code);
			return;
		}
		if (nickname == null || nickname.length() <= 2) {
			showAlert(R.string.remind, R.string.home_reg_error_nick);
			return;
		}
		if (team_access_code != null && team_access_code.trim().length() > 0) {
			if (team_access_code.trim().length() != 6) {
				showAlert(R.string.remind, R.string.home_reg_error_access_code);
				return;
			}
		} else {
			final HomeRegisterActivity context = HomeRegisterActivity.this;
			AlertDialog.Builder buidler = new AlertDialog.Builder(this);
			buidler.setMessage(R.string.home_reg_access_code_warning);
			buidler.setPositiveButton(R.string.home_no,
					new DialogInterface.OnClickListener() {
						/*
						 * (non-Javadoc)
						 * 
						 * @see android.content.DialogInterface.OnClickListener
						 * #onClick(android.content.DialogInterface, int)
						 */
						public void onClick(DialogInterface dialog, int which) {
							// 用户登录
							new RegisterUserTask(context,
									R.string.home_wait_title,
									R.string.home_wait_register)
									.execute(new Object());
						}
					});
			buidler.setNegativeButton(R.string.home_yes,
					new DialogInterface.OnClickListener() {
						/*
						 * (non-Javadoc)
						 * 
						 * @see android.content.DialogInterface.OnClickListener
						 * #onClick(android.content.DialogInterface, int)
						 */
						public void onClick(DialogInterface dialog, int which) {
							((EditText) context
									.findViewById(R.id.home_reg_team_access_code))
									.requestFocus();
						}
					});
			buidler.show();
			return;
		}

		// 用户登录
		new RegisterUserTask(this, R.string.home_wait_title,
				R.string.home_wait_register).execute(new Object());
	}

	/**
	 * Get the vlaidate code
	 * 
	 * @param view
	 *            the view
	 */
	public void validateCode(View view) {
		String phoneNumber = ((EditText) this
				.findViewById(R.id.home_reg_mobile)).getText().toString();
		if (phoneNumber == null || phoneNumber.length() <= 0) {
			showAlert(R.string.remind, R.string.home_reg_error_phone_number);
			return;
		}
		(new GetValidationCodeTask(this, R.string.home_wait_title,
				R.string.home_wait)).execute(phoneNumber);
	}

	/**
	 * 退出登录
	 * 
	 * @param view
	 *            the button of the logout button
	 */
	public void logout(View view) {
		AlertDialog.Builder buidler = new AlertDialog.Builder(this);
		buidler.setTitle(R.string.home_reg_logout);
		buidler.setMessage(R.string.home_reg_logout_confirm);

		buidler.setPositiveButton(this.getString(R.string.home_confirm),
				new OnClickListener() {
					public void onClick(DialogInterface arg0, int arg1) {
						// 清楚所有信息
						IMDroid.clear();
						HomeRegisterActivity.this.startActivity(new Intent(
								HomeRegisterActivity.this,
								HomeLoginActivity.class));
						HomeRegisterActivity.this.finish();
						if (MainActivity.instance != null) {
							MainActivity.instance.finish();
						}
					}
				});
		buidler.setNegativeButton(this.getString(R.string.home_cancel),
				new OnClickListener() {
					public void onClick(DialogInterface arg0, int arg1) {
					}
				});
		buidler.show();
	}

	/**
	 * Match the device
	 * 
	 * @param view
	 *            the button of the match
	 */
	public void match(View view) {
		int parentId = IMDroid.getUser().getParentId();
		if (parentId > 0) {
			String deviceName = this.getResources().getString(
					R.string.home_match_confirm);

			deviceName = deviceName.replace("#1#", IMDroid.getUser()
					.getParentId() + "");
			deviceName = deviceName.replace("#2#", IMDroid.getUser()
					.getParentName() + "");

			AlertDialog.Builder buidler = new AlertDialog.Builder(this);
			buidler.setTitle(R.string.home_match_confirm_title);
			buidler.setMessage(deviceName);

			buidler.setPositiveButton(this.getString(R.string.home_confirm),
					new OnClickListener() {
						public void onClick(DialogInterface arg0, int arg1) {
							startActivity(new Intent(HomeRegisterActivity.this,
									MatchActivity.class));
							finish();
						}
					});
			buidler.setNegativeButton(this.getString(R.string.home_cancel),
					new OnClickListener() {
						public void onClick(DialogInterface arg0, int arg1) {
						}
					});
			buidler.show();
		} else {
			startActivity(new Intent(this, MatchActivity.class));
			finish();
		}
	}

	/**
	 * Fill the user information into the form
	 * 
	 * @param user
	 *            the user
	 */
	private void feedUserInformation(User user) {
		// 用户账号
		((EditText) this.findViewById(R.id.home_reg_account)).setText(user
				.getUser_name());
		((EditText) this.findViewById(R.id.home_reg_account)).setEnabled(false);
		// 昵称
		((EditText) this.findViewById(R.id.home_reg_nick)).setText(user
				.getNickname());
		// 电话账号
		((EditText) this.findViewById(R.id.home_reg_mobile)).setText(user
				.getMobile_phone());
		((EditText) this.findViewById(R.id.home_reg_team_access_code))
				.setText(user.getTeam_access_code());
		// 车型
		((EditText) this.findViewById(R.id.home_reg_model)).setText(user
				.getVechile_model());
		// 车牌号
		((EditText) this.findViewById(R.id.home_reg_boardplate)).setText(user
				.getBoard_plate());
		String deviceName = this.getResources().getString(
				R.string.home_match_device_name);

		deviceName = deviceName.replace("#1#", user.getParentId() + "");
		deviceName = deviceName.replace("#2#", user.getParentName() + "");
		// 对应车机名称
		((EditText) this.findViewById(R.id.home_reg_text_match_device_edit))
				.setText(deviceName);

	}

	protected class GetValidationCodeTask extends ProgressBarAsyncTask {
		/**
		 * The constructor
		 * 
		 * @param context
		 *            the application context
		 * @param titleText
		 *            the title text
		 * @param messageText
		 *            the message text
		 */
		public GetValidationCodeTask(BaseActivity context, int titleText,
				int messageText) {
			super(context, titleText, messageText);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see com.imdroid.lite.activities.BaseActivity.ProgressBarAsyncTask#
		 * doInBackground(java.lang.Object[])
		 */
		protected Exception doInBackground(Object... params) {
			UserProcess process = (UserProcess) ProcessFactory
					.getProcess(UserProcess.class);
			try {
				process.getNewRegisterCode((String) params[0]);
			} catch (Exception e) {
				return e;
			}
			return null;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		protected void onPostExecute(Exception result) {
			super.onPostExecute(result);

			if (result == null) {
				context.showAlert(context.getString(R.string.home_reg_sms_send));
			} else {
				Toast.makeText(context, result.getMessage(), Toast.LENGTH_SHORT)
						.show();
			}
		}
	}

	/**
	 * The task of register the user
	 * 
	 */
	protected class RegisterUserTask extends ProgressBarAsyncTask {
		/**
		 * The constructor
		 * 
		 * @param context
		 *            the application context
		 * @param titleText
		 *            the title text
		 * @param messageText
		 *            the message text
		 */
		public RegisterUserTask(BaseActivity context, int titleText,
				int messageText) {
			super(context, titleText, messageText);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see com.imdroid.lite.activities.BaseActivity.ProgressBarAsyncTask#
		 * doInBackground(java.lang.Object[])
		 */
		protected Exception doInBackground(Object... params) {
			UserProcess process = (UserProcess) ProcessFactory
					.getProcess(UserProcess.class);

			// 判断是新加用户还是用户修改
			User user = new User();
			if (!isNew) {
				User oldU = IMDroid.getUser();
				user.setUser_id(oldU.getUser_id());
				user.setParentId(oldU.getParentId());
				user.setParentName(oldU.getParentName());
				user.setSim_number(oldU.getSim_number());
				user.setType(oldU.getType());
			}
			user.setUser_name(account);
			user.setNickname(nickname);
			user.setVechile_model(modal);
			user.setMobile_phone(mobile_phone);
			if (isNew || (password != null && password.length() >= 4)) {
				user.setPassword(password);
			}
			user.setBoard_plate(boardplate);
			user.setTeam_access_code(team_access_code);
			try {
				if (isNew) {
					// 在本机注册用户
					User currentUser = process.registerVistor(user,
							validate_code);
					IMDroid.registerUser(currentUser);
				} else {
					process.udateUser(user);
				}
				return null;
			} catch (Exception ex) {
				return ex;
			}
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		protected void onPostExecute(Exception result) {
			super.onPostExecute(result);
			if (result != null) {
				Toast.makeText(context, result.getMessage(), Toast.LENGTH_SHORT)
						.show();
				return;
			}
			// 流转到注册页面
			if (isNew)
				startActivity(new Intent(HomeRegisterActivity.this,
						MainActivity.class));

			finish();
		}
	}
}
